package com.salesmanager.core.business.customer.service;



import com.salesmanager.core.business.customer.dao.CustomerDAO;
import com.salesmanager.core.business.customer.model.*;

import com.salesmanager.core.business.generic.exception.ServiceException;
import com.salesmanager.core.business.generic.service.SalesManagerEntityServiceImpl;
import com.salesmanager.core.business.statistics.model.*;
import com.salesmanager.core.business.statistics.model.CustomerStatisticsCriteria;

import com.salesmanager.core.business.user.model.Group;
import com.salesmanager.core.business.user.model.GroupType;
import com.salesmanager.core.business.user.service.GroupService;
import com.salesmanager.core.utils.EncryptionUtil;
import com.salesmanager.web.model.paging.PaginationDataList;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service("customerService")
public class CustomerServiceImpl extends SalesManagerEntityServiceImpl<Long, Customer> implements CustomerService {

    private static final Logger LOGGER = LoggerFactory.getLogger(CustomerServiceImpl.class);

    private CustomerDAO customerDAO;

    @Autowired
    GroupService groupService;

    @Autowired
    public CustomerServiceImpl(CustomerDAO customerDAO) {
        super(customerDAO);
        this.customerDAO = customerDAO;
    }

    @Override
    public Customer getById(Long id) {
        return customerDAO.getById(id);
    }

    @Override
    public Customer getByTelphone(String telphone) {
        return customerDAO.getByTelphone(telphone);
    }

    @Override
    public void saveOrUpdate(Customer customer) throws ServiceException {

        LOGGER.debug("Creating Customer");

        if (customer.getId() != null && customer.getId() > 0) {
            super.update(customer);
        } else {
            super.create(customer);

        }
    }

    @Override
    public boolean saveSignUpUser(CustomerCriteria customerCriteria) throws ServiceException {
        CustomerAuths auth = customerDAO.getCustomerAuthByAuthType(customerCriteria);
        if (auth != null)
            return false;
        Customer customer = new Customer();
        customer.setEmailAddress("");
        customer.setNick(customerCriteria.getNick());
        customer.setTelphone(customerCriteria.getMobilePhone());
        customer.setDeviceToken(customerCriteria.getDeviceToken());
        customer.setChannel(customerCriteria.getChannel());

        String encodedPassword = null;
        if (customerCriteria.getAuthType() == 1) {
            encodedPassword = EncryptionUtil.encode(EncryptionUtil.SHA1, customerCriteria.getPassword());
        }

        //账号密码
        CustomerAuths customerAuths = new CustomerAuths();
        customerAuths.setIdentityType(customerCriteria.getAuthType());
        //手机登陆
        if (customerCriteria.getAuthType() == 1) {
            customerAuths.setIdentifier(customerCriteria.getMobilePhone());
            //deviceId登陆 不需要密码
        } else if (customerCriteria.getAuthType() == 2) {
            customerAuths.setIdentifier(customerCriteria.getDeviceId());
        }

        customerAuths.setCertificate(encodedPassword);
        customerAuths.setCreateTime(new Date());
        customerAuths.setStatus(1);
        customerAuths.setCustomer(customer);
        customer.getAuths().add(customerAuths);

        //初始化账户
        CustomerAccount customerAccount = new CustomerAccount();
        customerAccount.setBalance(new BigDecimal(0));
        customerAccount.setFrozen(false);
        customerAccount.setGold(new BigDecimal(0));
        customerAccount.setIntegral(0);
        customerAccount.setLevel(1);
        customer.setCustomerAccount(customerAccount);
        customerAccount.setCustomer(customer);
        List<Group> lGroup = groupService.listGroup(GroupType.CUSTOMER);
        Group group;
        if (lGroup.size() > 0) {
            group = lGroup.get(0);
            ArrayList<Group> list = new ArrayList<Group>();
            list.add(group);
            customer.setGroups(list);
        } else {
            return false;
        }
        //保存用户
        saveOrUpdate(customer);
        return true;
    }


    @Override
    public boolean saveDeviceToke(String username, String deviceToke, String appKey) {
        return customerDAO.saveDeviceToke(username, deviceToke, appKey);
    }

    @Override
    public boolean validateCustomer(String username, String password) {
        //手机号码登陆方式
        CustomerCriteria customerCriteria = new CustomerCriteria();
        customerCriteria.setMobilePhone(username);
        customerCriteria.setAuthType(1);

        //查询账号
        CustomerAuths customerAuths = this.customerDAO.getCustomerAuthByAuthType(customerCriteria);

        return customerAuths != null && EncryptionUtil.encode(EncryptionUtil.SHA1, password).equals(customerAuths.getCertificate());
    }

    @Override
    public CustomerAuths getCustomerAuthByDeviceId(String deviceId) {
        //DeviceID登陆方式
        CustomerCriteria customerCriteria = new CustomerCriteria();
        customerCriteria.setDeviceId(deviceId);
        customerCriteria.setAuthType(2);

        return this.customerDAO.getCustomerAuthByAuthType(customerCriteria);
    }


    @Override
    public boolean updatePassword(String username, String newpassword) throws ServiceException {
        Customer dbCustomer = customerDAO.getByTelphone(username);
        if (dbCustomer == null)
            return false;

        for (CustomerAuths customerAuths : dbCustomer.getAuths()) {
            if (customerAuths.getIdentityType() == 1) {
                customerAuths.setCertificate(EncryptionUtil.encode(EncryptionUtil.SHA1, newpassword));
            }
        }

        saveOrUpdate(dbCustomer);
        return true;
    }

    @Override
    public PaginationDataList<StatisticsEntityForCustomer> listWithCustomer(CustomerStatisticsCriteria criteria) throws ServiceException {
        return customerDAO.listWithCustomer(criteria);
    }


    @Override
    public Customer getCustomer(Long id) {
        return customerDAO.getCustomer(id);
    }


    @Override
    public int getCustomerCount(String startTime, String endTime) throws ParseException {
        return customerDAO.getCustomerCount(startTime, endTime);
    }

}
